//
//  SearchResultTableViewController.swift
//  NewsAPP
//
//  Created by URNing B on 2021/5/29.
//

import UIKit

class SearchResultTableViewController: UITableViewController, UISearchResultsUpdating{

    var Result : [[String : AnyObject]] = []
    override func viewDidLoad() {
        tableView.rowHeight = 130
        super.viewDidLoad()
        let xib = UINib(nibName: "SearchTableViewCell", bundle: nil)
        tableView.register(xib, forCellReuseIdentifier: "SearchNewsCell")
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    func updateSearchResults(for searchController: UISearchController) {
        guard let searchString = searchController.searchBar.text else {
            return
        }
        if searchString.isEmpty{ return }
        let sqlite = SQLiteManager.sharedInstance
        
        if !sqlite.openDB(){return}
        let queryResult = sqlite.execQuerySQL(sql: "SELECT * FROM CollectionNews WHERE title LIKE '%\(searchString)%'")
        
        if queryResult != nil
        {
            Result = queryResult!
            for row in queryResult!
            {
                print(row)
            }
        }
        tableView.reloadData()
    }
    
    // MARK: - Table view data source


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return Result.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SearchNewsCell", for: indexPath) as! SearchTableViewCell
        
        cell.SearchTitle.text! = (Result[indexPath.row]["title"] as! String)
        cell.SearchTime.text! = (Result[indexPath.row]["passtime"] as! String)

        let urlNet = URL(string: Result[indexPath.row]["image"] as! String)
        let task = URLSession.shared.dataTask(with: urlNet!)
        {
            (data,respones,error)in
            if let nsd = data{
                DispatchQueue.main.async {
                    cell.SearchImage.image = UIImage(data: nsd)
                }
            }
        }
        task.resume()

        // Configure the cell...

        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let mainstoryboard = UIStoryboard(name: "Main", bundle: nil)
        let detailVC = mainstoryboard.instantiateViewController(identifier: "DetailVC") as! CollectionDetailViewController
        let nav = self.presentingViewController?.navigationController
        detailVC.newsPath = Result[indexPath.row]["path"] as! String
        nav?.pushViewController(detailVC,animated:true)
        
        
    }
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    

}
